package com.base.saas.delivery.trace;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 王清亮
 * @date 2025/8/9 22:55
 * @description TODO
 */
@Component
public class TraceFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        try {
            // 从请求头获取追踪信息
            String traceId = httpRequest.getHeader(TraceContext.TRACE_ID);
            String spanId = httpRequest.getHeader(TraceContext.SPAN_ID);

            // 放入MDC上下文
            if (traceId != null) {
                MDC.put(TraceContext.TRACE_ID, traceId);
            }
            if (spanId != null) {
                MDC.put(TraceContext.SPAN_ID, spanId);
            }

            chain.doFilter(request, response);
        } finally {
            // 请求完成后清除MDC
            MDC.clear();
        }
    }
}